import { getRoutes } from '@/apis/system/user';
import { defineStore } from 'pinia';
import router, { route404, RouteNameEnum, routes, dynamicRoutes as dyRoutes } from '@/router';
import { transformBackendRoutes } from '@/utils/route-converter';
import { useHasPermi } from '@/hooks/useHasPermi';

export const usePermissionStore = defineStore('permissionStore', {
  state: () => ({
    layoutRoutes: [] as any[], // layout 路由
  }),
  getters: {},
  actions: {
    async generateRoutes() {
      try {
        const res = await getRoutes();
        const asyncRoutes = transformBackendRoutes(res.data);
        // Layout 路由
        const layoutRoute: any = routes.find((r) => r.name === RouteNameEnum.LAYOUT_ROOT);

        if (layoutRoute) {
          // 合并到 children 中
          layoutRoute.children = [...(layoutRoute.children || []), ...asyncRoutes];
          // 设置 layout 路由
          this.layoutRoutes = layoutRoute.children;
        }
        asyncRoutes.forEach((r) => {
          router.addRoute(RouteNameEnum.LAYOUT_ROOT, r);
        });

        const dynamicRoutes = filterDynamicRoutes(dyRoutes);

        dynamicRoutes.forEach((r) => {
          router.addRoute(RouteNameEnum.LAYOUT_ROOT, r); // 动态添加可访问路由表
        });

        router.addRoute(route404); // 添加 404 路由
      } catch (error) {
        console.log(error);
      }
    },
  },
});

export function filterDynamicRoutes(routes: any[]) {
  const hasPermi = useHasPermi();
  const res: any[] = [];
  routes.forEach((route) => {
    if (route.permissions) {
      if (hasPermi(route.permissions)) {
        res.push(route);
      }
    }
  });
  return res;
}
